import { createWebHashHistory, createRouter } from "vue-router";
import { ElMessage } from 'element-plus';
//路由负责页面跳转

// 导入页面组件
// ../是引入上一级的意思
import index from '../view/index.vue';
import member from '../view/member.vue';
import fruit from '../view/fruit.vue';
import harvest from '../view/harvest.vue';
import inventory from '../view/inventory.vue';
import inventoryWarning from '@/view/inventory-warning.vue';
import donationList from '../view/donation.vue';
import donationTotal from '@/view/donation-total.vue';
import login from '../view/login.vue';
import register from '../view/register.vue';
import adminDashboard from '../view/dashboard.vue';
import userHome from '../view/home.vue'; // 普通用户首页
import orderDetail from '@/view/order_detail.vue';
import orders from '@/view/orders.vue';

// 路由守卫：验证登录状态和权限
const checkAuth = (to, from, next) => {
    const token = localStorage.getItem('token');
    if (!token) return next('/login'); // 如果没有登录，跳转到登录页

    //获取用户的信息和角色
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    const userRole = userInfo.role || '';

    // 如果是管理员，允许访问所有页面
    if (userRole === 'admin') {
        return next(); // 允许访问
    }

    // 如果是普通用户，但访问了需要管理员权限的页面
    if (to.meta.requireAdmin) {
        ElMessage.warning('您没有访问权限');
        return next('/user/home'); // 普通用户访问管理员页面，跳转到用户首页
    }

    // 如果是普通用户，且访问的是普通用户的页面，允许访问
    next();
};

// 公共路由（无需登录）
const publicRoutes = [
    {
        path: '/login',
        name: 'Login',
        component: login,
        beforeEnter: (to, from, next) => {
            //如果已经登录，根据角色重定向到响应首页
            if (localStorage.getItem('token')) {
                const userRole = JSON.parse(localStorage.getItem('userInfo') || '{}').role;
                next(userRole === 'admin' ? '/admin/dashboard' : '/user/home');
            } else {
                next();
            }
        }
    },
    {
        path: '/register',
        name: 'Register',
        component: register
    }
];

// 主路由（需要登录）
const mainRoutes = [
    {
        path: '/',
        name: 'MainLayout',
        component: index,
        beforeEnter: checkAuth, // 应用路由守卫
        children: [
            // 公共子路由（所有登录用户可访问）
            {
                path: '/fruit/list',
                name: 'FruitList',
                component: fruit,
                meta: { title: '水果列表' },
                beforeEnter: checkAuth,
            },
            {
                path: '/fruit/harvest',
                name: 'HarvestRecord',
                component: harvest,
                meta: { title: '收获记录' },
                beforeEnter: checkAuth,
            },

            // 普通用户专属路由
            {
                path: '/user/home',
                name: 'UserHome',
                component: userHome,
                meta: { title: '用户首页' },
                beforeEnter: checkAuth,
            },
            {
                path: '/user/buyer',
                name: 'BuyerList',
                component: member,
                meta: { title: '买家列表' },
                beforeEnter: checkAuth,
            },
            {
                path: '/donation/total',
                name: 'DonationTotal',
                component: donationTotal,
                meta: { title: '爱心总览' },
                beforeEnter: checkAuth,
            },

            // 管理员专属路由（添加requireAdmin标记）
            {
                path: '/admin/dashboard',
                name: 'AdminDashboard',
                component: adminDashboard,
                meta: {
                    title: '管理员首页',
                    requireAdmin: true // 标记为管理员专属
                },
                beforeEnter: checkAuth,
            },
            {
                path: '/user/admin',
                name: 'AdminList',
                component: member,
                meta: {
                    title: '管理员列表',
                    requireAdmin: true // 标记为管理员专属
                },
                beforeEnter: checkAuth,
            },
            {
                path: '/inventory/list',
                name: 'Inventory',
                component: inventory,
                meta: { title: '库存列表', requireAdmin: true },
                beforeEnter: checkAuth,
            },
            {
                path: '/inventory/warning',
                name: 'InventoryWarning',
                component: inventoryWarning,
                meta: { title: '库存预警', requireAdmin: true },
                beforeEnter: checkAuth,
            },
            {
                path: '/order/list',
                name: 'Orders',
                component: orders,
                meta: { title: '订单列表' ,requireAdmin: true},
                beforeEnter: checkAuth,
            },
            {
                path: '/order/detail',
                name: 'OrderDetail',
                component: orderDetail,
                meta: { title: '订单明细',requireAdmin: true }
            },
            {
                path: '/donation/list',
                name: 'DonationList',
                component: donationList,
                meta: { title: '捐赠记录' ,requireAdmin: true},
                beforeEnter: checkAuth,
            },
        ]
    }
];

// 合并路由并添加404处理
const routes = [
    ...publicRoutes,
    ...mainRoutes,
    {
        path: '/:pathMatch(.*)*',
        redirect: (to) => {
            // 根据登录状态和角色重定向404页面
            const token = localStorage.getItem('token');
            if (!token) return '/login';

            const userRole = JSON.parse(localStorage.getItem('userInfo') || '{}').role;
            return userRole === 'admin' ? '/admin/dashboard' : '/user/home';
        }
    }
];

//创建路由实例
const router = createRouter({
    //使用哈希模式创建路由历史
    history: createWebHashHistory(),
    routes
});

// 全局后置钩子：设置页面标题
router.afterEach((to) => {
    document.title = to.meta.title || '农村爱心水果售卖系统';
});
//导出路由实例：供 Vue 应用注册使用
export default router;
